import { AxiosRequestConfig, AxiosPromise, Method } from './../constant/index'
import dispatchRequest from './dispatchRequest'
/*
 * @Descripttion: Axios核心类
 * @version:
 * @Author: yangzhihao
 * @Date: 2021-07-14 14:57:59
 * @LastEditors: yangzhihao
 * @LastEditTime: 2021-07-14 15:34:36
 */
export default class Axios {
  // 这里其实就是之前实现的axios，本身就是一个函数
  request(url: any, config?: any): AxiosPromise {
    if (typeof url === 'string') {
      // 未传入参数 axios('/test')
      if (!config) {
        config = {}
      }
      // 传入config，config的url合入config当中
      config.url = url
    } else {
      // 如果之传入一个对象，也就是axios({}),这时将url当做config对象即可
      config = url
    }
    return dispatchRequest(config)
  }
  // 扩展API

  get(url: string, config?: AxiosRequestConfig): AxiosPromise {
    return this._requestMethodWithoutData('get', url, config)
  }

  delete(url: string, config?: AxiosRequestConfig): AxiosPromise {
    return this._requestMethodWithoutData('delete', url, config)
  }

  head(url: string, config?: AxiosRequestConfig): AxiosPromise {
    return this._requestMethodWithoutData('head', url, config)
  }

  options(url: string, config?: AxiosRequestConfig): AxiosPromise {
    return this._requestMethodWithoutData('options', url, config)
  }

  post(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise {
    return this._requestMethodWithData('post', url, data, config)
  }
  put(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise {
    return this._requestMethodWithData('put', url, data, config)
  }
  patch(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise {
    return this._requestMethodWithData('patch', url, data, config)
  }

  // 合并混合属性,无参数
  _requestMethodWithoutData(method: Method, url: string, config?: AxiosRequestConfig) {
    return this.request(
      Object.assign(config || {}, {
        method,
        url
      })
    )
  }
  _requestMethodWithData(method: Method, url: string, data?: any, config?: AxiosRequestConfig) {
    return this.request(
      Object.assign(config || {}, {
        method,
        url,
        data
      })
    )
  }
}
